package com.cuiyun97.utils;

import com.alibaba.fastjson.JSONObject;
import com.cuiyun97.domain.po.SetSms;
import com.cuiyun97.service.SetSmsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

/**
 * ali 短信发送工具类
 */
@Component
public class AliSmsUtil {

    @Resource
    private SetSmsService setSmsService;

    private Client createClient(SetSms set) throws Exception {

        Config config = new Config()
                .setAccessKeyId(set.getAccessKeyId())
                .setAccessKeySecret(set.getAccessKeySecret());
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        // config.endpoint = "dysmsapi.ap-southeast-1.aliyuncs.com";
        config.endpoint = set.getEndpoint();
        return new Client(config);
    }

    public void send(String phone, String code) throws Exception {

        // 获取数据库配置信息
        SetSms set = setSmsService.getLastOne();

        HashMap<String, String> map = new HashMap<>();
        // 这里要对应模板
        map.put(set.getCode(), code);

        Client client = this.createClient(set);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(set.getSign())
                .setTemplateCode(set.getTemplate())
                .setPhoneNumbers(phone)
                .setTemplateParam(JSONObject.toJSONString(map));
        // .setTemplateParam(code);

        try {
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
            // SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if (sendSmsResponse.getStatusCode() == 200) {
                System.out.println("发送成功");
            }
        } catch (Exception e) {
            System.out.println("短信错误: " + e.getMessage());
        }
    }

}
